using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using Palaso.Reporting;
using SpellCenter.Core;
using SpellCenter.UI.FileChoosing;
using SpellCenter.UI.Properties;

namespace SpellCenter.UI
{
    public partial class WordStatusForm : Form
    {
        private readonly FileIndexingDialog _progressDialog;
        private IUIFunctions _utility;

        public IUIFunctions Utility
        {
            get { return _utility; }
            set { _utility = value; }
        }

        public WordStatusForm()
        {
            InitializeComponent();
            Utility = new UIFunctions();
            InitWindowSize();
            if (DesignMode)
                return;
            _spellGridControl.ContextControl = _wordContextControl;
            _progressDialog = new FileIndexingDialog();
            _spellStatusEditor.SpellGrid = _spellGridControl;
            _spellStatusEditor.ProgressBar = _progressDialog;
            RegisterEvents();
        }

        private int MenuBlockBottom
        {
            get { return _corpusSettingsButton.Bottom; }
        }

        private void SaveHeightsInConfig()
        {
            Settings.Default.WindowSize = Size;
            Settings.Default.Form_SplitterDistance = _splitContainer.SplitterDistance;
            Settings.Default.Save();
        }
        private void InitWindowSize()
        {
            Size = Settings.Default.WindowSize;
            _splitContainer.SplitterDistance = Settings.Default.Form_SplitterDistance;
        }

        #region Event Handlers

        private void RegisterEvents()
        {
            Closing += Form_Closing;
            Resize += WordStatusForm_Resize;
            Load += WordStatusForm_Resize;
            Shown += WordStatusForm_Shown;
            Activated += WordStatusForm_Activated;
            _wordContextControl.Waiting += WordContextControl_Waiting;
            _wordContextControl.DoneWaiting += WordContextControl_DoneWaiting;
            _progressDialog.Finished += _spellGridControl.HandleIndexingFinished;
            _corpusSettingsButton.Click += CorpusSettingsButton_Click;
        }

        private void WordStatusForm_Activated(object sender, EventArgs e)
        {
            if(!_spellGridControl.Model.IsCorpusUpToDate())
            {
                LoadCorpus(_spellGridControl.Model.Config, string.Empty);
            }
        }

        private void WordStatusForm_Shown(object sender, EventArgs e)
        {
            string loadThisFile = Settings.Default.LastOpenProject;
            if (!string.IsNullOrEmpty(loadThisFile))
            {
                LoadCorpus(loadThisFile);
            }
            else NewCorpusFromUser();
        }

        private void WordContextControl_DoneWaiting(object sender, EventArgs e)
        {
            Cursor = Cursors.Default;
        }

        private void WordContextControl_Waiting(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            if(!e.Alt && !e.Control && !e.Shift && !_spellStatusEditor.IsInEditMode)
                _spellStatusEditor.HandleKeyCode(e.KeyCode);
        }

        private void CorpusSettingsButton_Click(object sender, EventArgs e)
        {
            NewCorpusFromUser();
        }

        #region New Corpus (or something like that)

        private FileChooserForm _chooser;
        private void NewCorpusFromUser()
        {
            if(_chooser == null)
            {
                _chooser = new FileChooserForm();
                _chooser.Finished += delegate { LoadCorpus(_chooser.Result, _chooser.DictionaryFile); };
            }
            else _chooser.Reset(_spellGridControl.Model.Config);
            _chooser.Visible = false; //need to make sure it's not visible so we can show it (and surprise people)
            _chooser.Show(this);
        }

        private void LoadCorpus(string fileDialog)
        {
            if (fileDialog != null)
            {
                _progressDialog.Show(ParentForm);
                _spellGridControl.InitializeCorpus(fileDialog, _progressDialog);
                Text = "Spell Center - " + _spellGridControl.Model.Config.WritingSystemId;
            }
        }
        private void LoadCorpus(FilesInCorpusList config, string dictFile)
        {
            try
            {
                if(!_progressDialog.Visible)
                    _progressDialog.Show(ParentForm);
                _spellGridControl.InitializeCorpus(config, _progressDialog);
                Text = "Spell Center - " + _spellGridControl.Model.Config.WritingSystemId;
                if (!string.IsNullOrEmpty(dictFile))
                {
                    _spellGridControl.Model.ImportDictionary(dictFile);
                }
            }
            catch (InvalidOperationException e)
            {
#if DEBUG
                ErrorNotificationDialog.ReportException(e, this, false);
#endif
            }
        }

        #endregion

        private void Form_Closing(object sender, CancelEventArgs e)
        {
            SaveHeightsInConfig();
        }

        private void WordStatusForm_Resize(object sender, EventArgs e)
        {
            _splitContainer.Location = new Point(ClientRectangle.X, MenuBlockBottom);
            int splitterDist = _splitContainer.SplitterDistance;
            _splitContainer.Size = new Size(ClientRectangle.Width, 
                                            ClientRectangle.Bottom - MenuBlockBottom);
            _splitContainer.SplitterDistance = splitterDist;
            _spellStatusEditor.SafeResize(Width);
        }

        private void FontSettingsButton_Click(object sender, EventArgs e)
        {
            FontDialog dialog = new FontDialog();
            dialog.Font = Settings.Default.GridFont;
            dialog.ShowEffects = false;
            dialog.ShowDialog(this);
            _spellGridControl.SetFont(dialog.Font);
            _wordContextControl.SetFont(dialog.Font);
        }

        private void ExportDictionaryButton_Click(object sender, EventArgs e)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "Dictionary Files (*.dic)|*.dic|All Files (*.*)|*.*";
            if (dialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                string name = dialog.FileName;
                _spellGridControl.Model.ExportDictionary(name);
            }
        }

        #endregion
    }
}